import 'dart:collection';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'ad_jg_flutter_sdk.dart';
import 'ad_jg_ad.dart';

abstract class ADJgAd {
  int adId = 0;

  void Function(AdInfo adInfo)? onSucced;
  void Function(AdErrorInfo adErrorInfo)? onFailed;
  void Function(AdInfo adInfo)? onClosed;
  void Function(AdInfo adInfo)? onClicked;
  void Function(AdInfo adInfo)? onExposed;

  // rewardAd only
  void Function(AdInfo adInfo)? onRewarded;

  // nativeAd only
  void Function(ADJgFlutterNativeAdView adView)? onReceived;

  void regist() {
    adId = instanceManager.regist(this);
  }

  void resetAdId() {
    adId = instanceManager.resetAdId(this);
  }

  void unregist() {
    AdJgFlutterSdk.releaseAd(adId: this.adId);
    instanceManager.unregist(this);
  }
}

class ADJgAdView extends ADJgAd {
  late double width;
  late double height;
}

class ADJgAdLoader extends ADJgAd {}

ADJgAdManager instanceManager = ADJgAdManager();

class ADJgAdManager {
  HashMap<int, dynamic> map = new HashMap();
  int adId = 0;
  int regist(ADJgAd ad) {
    int adId = ad.adId;
    if (ad.adId == 0) {
      this.adId += 1;
      adId = this.adId;
    }
    map[adId] = ad;
    return adId;
  }

  int resetAdId(ADJgAd ad) {
    int adId = ad.adId;
    if (map[adId] != null) {
      this.adId += 1;
      adId = this.adId;
    }
    map[adId] = ad;
    return adId;
  }

  void unregist(ADJgAd ad) {
    adId = ad.adId;
    map.remove(adId);
  }

  int adIdFor(ADJgAd ad) {
    return ad.adId;
  }

  ADJgAd adFor(int adId) {
    return map[adId];
  }
}

class ADJgWidget extends StatelessWidget {
  ADJgWidget({Key? key, required this.adView}) : super(key: key);

  final ADJgAdView adView;

  @override
  Widget build(BuildContext context) {
    if (Platform.isIOS) {
      return Container(
          width: this.adView.width,
          height: this.adView.height,
          child: UiKitView(
              viewType: "ADJgAdView",
              creationParams: instanceManager.adIdFor(this.adView),
              creationParamsCodec: StandardMessageCodec()));
    } else if (Platform.isAndroid) {
      return Container(
          width: this.adView.width,
          height: this.adView.height,
          child: AndroidView(
              viewType: "ADJgAdView",
              creationParams: instanceManager.adIdFor(this.adView),
              creationParamsCodec: StandardMessageCodec()));
    }
    return Container();
  }
}
